<!--添加农户信息-->

<script setup lang="ts">
import { ref, reactive, onMounted, onBeforeMount, getCurrentInstance, onBeforeUnmount } from "vue";
import type { TabsPaneContext } from "element-plus";
import HzBaseFrom from "@/views/credit/peasants/pea-message/components/hzBaseFrom.vue";
import { reqCreAdd, reqCreEdit, reqCrePeaInfoByHzId, reqUploadImage} from "@/api/credit/peasants/pea-message";
import Vue3Esign from "@/components/Vue3Esign/index.vue";
import HzFamilyNumberFrom from "@/views/credit/peasants/pea-message/components/hzFamilyNumberFrom.vue";
import HzFamFaZhanFrom from "@/views/credit/peasants/pea-message/components/hzFamFaZhanFrom.vue";
import { useRoute } from "vue-router";
import { useTagsViewStore } from "@/store/modules/tagsView";
import { base64ImgtoFile } from "@/utils/imageUtil";

/*农户表单*/
// 表单
const peaFrom = reactive({
  //////////////////////////////////////////////////////////////////////////////
  /*户主基本信息表*/
  hzId: "",

  hzName: "", //户主姓名
  hzSex: "",
  hzAge: "", //年龄
  hzPhoneNumber: "", //手机号码（户主）

  hzIdCardNumber: "", //身份证号码（户主）
  xingZhengArea: [], // 行政区域


  familyAddress: "", //家庭详细住址
  hzMarriage: "", //婚姻状况  点选择
  hzNation: "", //民族    下拉框选择

  hzIdCardFront: "", //身份证正面（户主） 单张照片地址
  hzIdCardReverse: "", //身份证反面（户主） 单张照片地址
  hzAddressPho: "", //户口住址页（户主） 单张照片地址

  hasInVillager: "", //是否为本村人   点选择
  familySize: "", //家庭人数  数字输入框
  familyLoaderSize: "", //家庭劳动力人数  数字输入框
  hasIll: "", //家庭成员是否有重疾病患者（长期住院或接受治疗） 点选择

  farmerType: [], //农户类型  多选框
  hasPingKunHu: "", //是否建档贫困户 单点选择
  maxXueLi: "", //家庭最高学历 下拉框

  hasLand: "", //是否有农村土地经营证书
  landArea: "", //承包面积（亩）
  canQuanNum: "", // 产权证编号

  landPho: [], //土地经营证书照片

  hasTransLand: "", //是否流转土地
  transArea: "", // 流转面积（亩）
  treeArea: "", // 山林面积
  treeDeedNum: "", //林权证编号
  treeDeedPho: [], // 林权证图片

  hasFrameHouse: "", // 是否有农房
  newDanger: "", // 农房新旧程度
  houseJieGou: "", // 农房结构
  houseHeight: "", // 农房楼层
  houseArea: "", // 农房面积


  //////////////////////////////////////////////////////////////////////////////
  /*家庭成员信息*/
  peaHzFamList: [], //家庭成员

  //////////////////////////////////////////////////////////////////////////////
  /*家庭产业状况*/

  mainYeWuYear: "", //主营业务经营年限       main_pro_years
  mainYeWuXiaQu: [], //主项目经营辖区        main_pro_area
  mainXiangMuAddress: "", //主要项目经营地址
  mainChanYe: [], //家庭主产业（多选） 种植，养殖，其他 fam_main_pro

  hasZaiHai: "", //近三年来生产是否受灾
  laoDongJiNeng: "", //劳动技能

  farming: [], //养殖项目
  croping: [], //种植项目

  famWuGongIncome: "", //家庭务工收入（元）
  famOtherIncome: "", // 家庭其他收入（元）

  shengChanExpend: "", // 生产支出/年(元)
  lifeExpend: "", // 家庭生活支出/年(元)

  hasLoans: "", //是否有金额贷款意向
  loansMoney: "", //意向贷款金额(元)


  //////////////////////////////////////////////////////////////////////////////
  /*签字确认后进行提交*/
  signUrl: "",

});

const { proxy }: any = getCurrentInstance()
const activeName = ref("first");
const loading = ref(false)  // 加载
const $route = useRoute();

const handleClick = (tab: TabsPaneContext, event: Event) => {
  console.log(tab, event);
};



// 重置数据
const reset = () => {
  Object.keys(peaFrom).forEach((key) => {
    if(key == "xingZhengArea"
      || key == "farmerType"
      || key == "landPho"
      || key == "treeDeedPho"
      || key == "peaHzFamList"
      || key == "mainXiangMuAddress"
      || key == "mainChanYe"
      || key == "farming"
      || key == "croping"
    ) peaFrom[key] = []
    else if(key == "ratingStatus") peaFrom[key] = "0"
    else peaFrom[key] = ""
  })
};

onBeforeMount(() => {
  // 对数据进行置空
  reset();
})

// 组件挂载之后进行
onMounted(async () => {
  // 进行初始化
  loading.value = true
  const hzId = $route.params && $route.params.hzId;
  if (hzId != 0) {
    // 表示是修改操作
    peaFrom.hzId = hzId;
    // 进行查询
    await reqCrePeaInfoByHzId(hzId).then((req) => {
      // 进行数据的赋值
      Object.keys(peaFrom).forEach(key => {
        peaFrom[key] = req.data[key];
      });
    });
  }
  setTimeout(() => {
    loading.value = false;
  }, 1000);
})


// 提交数据
const handleSubmit = async () => {
  try {
    // 进行表单验证
    await hzBaseFromRef.value.submitHzForm();
    await hzFamilyNumberFromRef.value.submitHzFamNumForm();
    await hzFamFaZhanFromRef.value.submitHzFamInForm();
    if (peaFrom.peaHzFamList.length != peaFrom.familySize) {
      proxy.$modal.msgError("请检查添加的家庭成员人数是否和填写的一致！");
      return
    }
    if (peaFrom.signUrl == "") {
      proxy.$modal.msgError("请签名后再提交！");
      return
    }
    proxy.$modal.confirm("确认提交信息吗？").then(async () => {
      // 添加操作
      if (peaFrom.hzId == undefined || peaFrom.hzId == "") {
        await reqCreAdd(peaFrom).then((req: reqBaseData) => {
          if (req.code == 200) {
            proxy.$modal.msgSuccess("添加成功！");
            handleClose();
          } else {
            proxy.$modal.msgError("添加失败，请稍后重试！");
          }
        }).catch((e) => {
        });
      } else  {
        // 修改操作
        await reqCreEdit(peaFrom).then((req: reqBaseData) => {
          if (req.code == 200) {
            proxy.$modal.msgSuccess("修改成功！");
          } else {
            proxy.$modal.msgError("修改失败，请稍后重试！");
          }
        }).catch((e) => {
        });
      }
    })
  } catch (e) {
    const messages: string[] = [];
    console.log(messages);

    traverse(data);
    console.log(messages);
    proxy.$modal.msgError(messages);
  }
};

// 关闭该路由
const handleClose = async () => {
  // const activeTabPath = $route.path;
  // if (isActive(activeTabPath)) {
  //   toLastView(activeTabPath);
  // }
  // await TagsViewStore.delView(activeTabPath);
  // 移除并进行跳转
  TagsViewStore.toLastView($route.path)
  TagsViewStore.delView($route.path)
  // 清空数据
  handleReset()
};

// 关闭该路由组件
const isActive = (path) => {
  return path === $route.path;
};

function toLastView(activeTabPath) {
  console.log(activeTabPath);
  let index = TagsViewStore.visitedViews.findIndex((item) => item.path === activeTabPath);
  const nextTab = TagsViewStore.visitedViews[index + 1] || TagsViewStore.visitedViews[index - 1];
  if (!nextTab) return;
  router.push(nextTab.path);
  TagsViewStore.addVisitedView(nextTab);
}


const lineWidth = ref(6);
const lineColor = ref("#409eff");
const bgColor = ref("");
const isCrop = ref(false);
const TagsViewStore = useTagsViewStore();
const ruleFormRef = ref<FormInstance>();
const hzBaseFromRef = ref();// 农户基本信息
const hzFamilyNumberFromRef = ref(); // 农户家庭信息
const hzFamFaZhanFromRef = ref(); // 农户发展产业


const esginRef: any = ref(null);

// 重置按钮
const handleReset = () => {
  hzFamFaZhanFromRef.value.removeFrom()
  esginRef.value.reset();
  reset()
};

// 上传签名
const handleGenerate = async () => {
  await esginRef.value.generate().then(async (res) => {
      //生成base64编码
      // 这里需要将其上传到服务器
      // 将 Base64 编码字符串解码为二进制数据
      let imgFile = base64ImgtoFile(res);
      /*将file进行上传*/
      const form = new FormData();
      form.set("file", imgFile);
      // 将该文件进行上传
      await reqUploadImage(form)
        .then((req) => {
          if (req.code == 200) {
            proxy.$modal.msgSuccess("上传成功");
            // 将图片的地址进行输出
            peaFrom.signUrl = req.fileName;
          }
        })
        .catch((err) => {});
    })
    .catch((err) => {
      proxy.$modal.msgSuccess(err); // 画布没有签字时会执行这里 'Not Signned'
    });
};

</script>

<template>
  <PageWrapLayout v-loading="loading">
    <!--下面是一个表单进行数据的收集      -->
    <div class="el-body">
      <div class="utils">
        {{ peaFrom }}
        <el-tabs v-model="activeName" class="demo-tabs" @tab-click="handleClick">
          <el-tab-pane label="户主信息采集" name="first" class="dashed-border">
            <el-scrollbar :noresize="true" height="100%" class="hide-scrollbar">
              <hzBaseFrom style="width: 95%;" ref="hzBaseFromRef" v-model:peaFrom="peaFrom"></hzBaseFrom>
            </el-scrollbar>
          </el-tab-pane>

          <el-tab-pane label="家庭成员信息" name="second" class="dashed-border">
            <el-scrollbar :noresize="true" height="100%" class="hide-scrollbar">
              <hzFamilyNumberFrom ref="hzFamilyNumberFromRef"
                                  v-model:peaHzFamList="peaFrom.peaHzFamList"
                                  v-model:familySize="peaFrom.familySize" :hz-id="peaFrom.hzId"></hzFamilyNumberFrom>
            </el-scrollbar>
          </el-tab-pane>

          <el-tab-pane label="家庭产业发展情况" name="third" class="dashed-border">
            <el-scrollbar :noresize="true" height="100%" class="hide-scrollbar">
              <hzFamFaZhanFrom ref="hzFamFaZhanFromRef" v-model:peaFrom="peaFrom"></hzFamFaZhanFrom>
            </el-scrollbar>
          </el-tab-pane>

          <el-tab-pane label="签字确认" name="fourth" class="dashed-border">
            <!-- 召唤签字框进行签字     -->
            <el-scrollbar :noresize="true" height="100%" class="hide-scrollbar">
              <el-divider content-position="left">签字图片展示</el-divider>
              <div class="demo-image__error">
                <div class="block">
                  <span class="demonstration">签名图片</span>
                  <el-image :src="proxy.$getServerUrl() + peaFrom.signUrl">
                    <template #error>
                      <div class="image-slot">
                        <el-icon><Picture /></el-icon>
                      </div>
                    </template>
                  </el-image>
                </div>
              </div>
              <el-divider content-position="left">签字区域 ---- 温馨提示：请在签完字后点击保存，否则将不会被修改掉
              </el-divider>
              <div class="vue3Esign">
                <div class="el-button-in">
                  <el-button type="warning" @click="handleReset">清空</el-button>
                  <el-button type="success" @click="handleGenerate">上传签名</el-button>
                </div>
                <Vue3Esign
                  ref="esginRef"
                  v-model:bg-color="bgColor"
                  :width="1000"
                  :height="500"
                  :is-crop="isCrop"
                  :line-width="lineWidth"
                  :line-color="lineColor"
                  class="esign"
                ></Vue3Esign>
              </div>
            </el-scrollbar>
          </el-tab-pane>
        </el-tabs>
      </div>
      <div class="last-page">
        <el-space wrap :size="35">
          <el-button type="warning" @click="handleReset">重置</el-button>
          <el-button type="success" @click="handleSubmit">提交</el-button>
        </el-space>
          <el-button type="danger" @click="handleClose">取消</el-button>
      </div>
    </div>
  </PageWrapLayout>
</template>

<style scoped lang="scss">
@import "./index";

.el-body {
  padding: 5px;
  width: calc(100% - 10px);

  .utils {
    width: 100%;
  }

  .el-tab-pane {
    width: 100%;
    height: calc(100vh - 300px);
  }

  .dashed-border {
    width: calc(100% - 32px);
    border: 1px dashed black;
    padding: 15px;
  }

  .last-page {
    //position: fixed;
    margin-top: 20px;
    bottom: 20px;
    right: 30px;
    margin-bottom: 10px;
    margin-right: 10px;
    display: flex;
    justify-content: right;
  }

}

.esign {
  border: black 1px dashed;
}

.el-form {
  font-weight: bold;
}

.el-dialog__title {
  font-weight: bold;
}

.el-image-s {
  border: black 1px dashed;
}

.vue3Esign {

  .esign {
  }

  .el-button-in {
    margin: 20px 20px;
  }
}

.demo-image__error .block {
  padding: 30px 0;
  text-align: center;
  display: inline-block;
  width: 49%;
  box-sizing: border-box;
  vertical-align: top;
}
.demo-image__error .demonstration {
  display: block;
  color: var(--el-text-color-secondary);
  font-size: 14px;
  margin-bottom: 20px;
}
.demo-image__error .el-image {
  padding: 0 5px;
  max-width: 300px;
  max-height: 200px;
  width: 100%;
  height: 200px;
}

.demo-image__error .image-slot {
  display: flex;
  justify-content: center;
  align-items: center;
  width: 100%;
  height: 100%;
  background: var(--el-fill-color-light);
  color: var(--el-text-color-secondary);
  font-size: 30px;
}
.demo-image__error .image-slot .el-icon {
  font-size: 30px;
}
</style>
